package lookas;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Date;

import javax.sql.DataSource;

import lookas.model.Person;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class Main{
    private static final Log log = LogFactory.getLog(Main.class);

    public static void main(String[] args) throws Exception{
        PersonGenerator generator = new PersonGenerator();
        for(long i = 0; i < 1000000000; i++){
            Person person = generator.next();
            save(person);
            System.out.println(i);
        }
    }

    public static void save(Person p) throws Exception{
        DataSource ds = setupDataSource();
        Connection con = ds.getConnection();
        PreparedStatement stmt;
        stmt = con.prepareStatement("insert into person(pesel, name) values (?,?)");
        stmt.setString(1, p.getPesel());
        stmt.setString(2, p.getFirstName() + " " + p.getSecondName());
        long time = new Date().getTime();
        try{
            stmt.executeUpdate();
            log.debug("czas:" + (new Date().getTime() - time));
        }catch(Exception e){
            log.debug(e.getMessage());
        }
        stmt.close();
        con.close();

    }

    public static void createTable() throws Exception{
        DataSource ds = setupDataSource();
        Connection con = ds.getConnection();
        PreparedStatement stmt;
        stmt = con.prepareStatement("create table person (name varchar(256) not null, pesel varchar(11) not null, "
            + "primary key(pesel))");
        stmt.execute();
        stmt.close();
        con.close();
    }

    private static DataSource setupDataSource(){
        BasicDataSource ds = new BasicDataSource();
        ds.setDriverClassName("org.apache.derby.jdbc.EmbeddedDriver");
        ds.setUsername("app");
        ds.setPassword("app");
        ds.setUrl("jdbc:derby:db_test;create=true");
        ds.setInitialSize(1);
        ds.setMinIdle(1);
        return ds;
    }
}
